import axios from 'axios'
import { Message } from 'element-ui'
import { getToken } from './cookie'

/**
 * 默认请求头
 */
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  //baseURL: process.env.VUE_APP_BASE_API,
  baseURL: 'https://zhangshaobin.utools.club',
  // 超时
  timeout: 10000
})
// 请求拦截器
service.interceptors.request.use(
  config => {
    const isToken = (config.headers || {}).isToken === false
    if (getToken() && !isToken) {
      // 让每个请求携带自定义token
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    console.log(error)
    Promise.reject(error)
  }
)

//响应拦截器
service.interceptors.response.use(res => {
  console.log(res)
  let result = res.data
  let code = result.code
  if (code === 0) {
    return result.data
  } else {
    Message({
      message: result.message,
      type: 'error'
    })
    return Promise.reject(new Error(result.message))
  }
})
export default service
